package com.tolerate.managespringboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tolerate.managespringboot.common.Result;
import com.tolerate.managespringboot.entity.RoleMenu;
import com.tolerate.managespringboot.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/roleMenu")
public class RoleMenuController {

    @Autowired
    private RoleMenuService roleMenuService;


    /**
     * 绑定角色和菜单的关系
     *
     * @param roleId  角色id
     * @param menuIds 菜单id数组
     * @return
     */
    @PostMapping("/setRoleMenu/{roleId}")
    @Transactional // 开始事务，同时执行成功，同时执行失败
    public Result setRoleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
        // 先删除已经绑定的数据
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId, roleId);
        roleMenuService.remove(lambdaQueryWrapper);

        // 新增绑定关系
        List<RoleMenu> roleMenuList = new ArrayList<>();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuList.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenuList);
        return Result.success();
    }

    @PostMapping("/getRoleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId) {
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId, roleId);
        List<RoleMenu> list = roleMenuService.list(lambdaQueryWrapper);

        // 获取菜单id集合
        List<Integer> menuIds = new ArrayList<>();
        for (RoleMenu roleMenu : list) {
            menuIds.add(roleMenu.getMenuId());
        }

        return Result.success(menuIds);
    }

}
